package com.xctech.yace.service;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.xctech.yace.dto.I2MetaDataDTO;
import com.xctech.yace.dto.MetaDataDTO;
import com.xctech.yace.factory.MybatisSessionFactory;
import com.xctech.yace.mapper.MetaDataMapper;
import com.xctech.yace.util.DateUtil;
import com.xctech.yace.util.DirUtil;
import com.xctech.yace.util.JsonNodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.ibatis.session.SqlSession;
import org.apache.kafka.clients.consumer.ConsumerRecord;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Slf4j
public class TradeO32Service {

    public static MetaDataMapper initMetaData(){
        String filePath = DirUtil.getOrgPath()+"conf/db.properties";
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = MybatisSessionFactory.getSqlSessionFactory(properties).openSession(true);
        MetaDataMapper mapper = sqlSession.getMapper(MetaDataMapper.class);
        return mapper;
    }

//    public static void main(String[] args) {
//        MetaDataMapper mapper = initMetaData();
//        try{
//            I2MetaDataDTO dto = new I2MetaDataDTO();
//            dto.setTopic("test");
//            dto.setPartition(1);
//            dto.setOffset(123455L);
//            dto.setTimestamp("20230000000");
//            dto.setInsertDate("20230506");
//            dto.setInsertTime("153000");
//            dto.setXid("Ox231231adsgausd");
//            dto.setOwner("TCURRENT");
//            dto.setOp(1);
//            dto.setOpType("INSERT");
//            dto.setBefore("{\n" +
//                    "        \"C_BUSIN_CLASS\": \"1\",\n" +
//                    "    }");
//            dto.setAfter("{\n" +
//                    "        \"C_BUSIN_CLASS\": \"1\",\n" +
//                    "        \"C_CANCEL_TIME\": null,\n" +
//                    "    }");
//            dto.setBeforeKey("{\n" +
//                    "        \"L_REALDEAL_SERIAL_NO\": \"54404\"\n" +
//                    "    }");
//            dto.setAfterKey("{\n" +
//                    "        \"L_REALDEAL_SERIAL_NO\": \"54404\"\n" +
//                    "    }");
//            mapper.saveI2MetaData(dto);
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }

    //解析及插入英方数据
    public static void praseAndInsert(ConsumerRecord<String, String> data, MetaDataMapper mapper){
        if(mapper == null){
            mapper = initMetaData();
        }
        try{
            I2MetaDataDTO dto = new I2MetaDataDTO();
            dto.setTopic(data.topic());
            dto.setPartition(data.partition());
            dto.setOffset(data.offset());
            dto.setTimestamp(data.timestamp()+"");
            dto.setInsertDate(DateUtil.getTodayDate());
            dto.setInsertTime(DateUtil.getTodayTime());
            String json = data.value();
            JsonNode jsonNode = null;
            try {
                jsonNode = JsonNodeUtil.getInstance().
                        configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true).
                        readValue(json, JsonNode.class);
            }catch (JsonParseException e){
                //提示消息头解析
                String headMsg = data.topic()+"_"+ data.partition() +":"+ data.offset();
                log.error("{}消息包体解析json失败,请检查数据,这里不做报错处理 row={}", headMsg,json);
            }
            String xid = JsonNodeUtil.getValueByPath(new Tuple3<>("root","xid",false), jsonNode);
            dto.setXid(xid);

            String owner = JsonNodeUtil.getValueByPath(new Tuple3<>("root","owner",false), jsonNode);
            dto.setOwner(owner);

            String op = JsonNodeUtil.getValueByPath(new Tuple3<>("root","op",false), jsonNode);
            dto.setOp(Integer.parseInt(op));

            String opType = JsonNodeUtil.getValueByPath(new Tuple3<>("root","optype",false), jsonNode);
            dto.setOpType(opType);

            String actseq = JsonNodeUtil.getValueByPath(new Tuple3<>("root","actseq",false), jsonNode);
            dto.setActseq(actseq);

            String before = JsonNodeUtil.getValueByPath(new Tuple3<>("root","before",false), jsonNode);
            dto.setBefore(before);

            String after = JsonNodeUtil.getValueByPath(new Tuple3<>("root","after",false), jsonNode);
            dto.setAfter(after);

            String beforeKey = JsonNodeUtil.getValueByPath(new Tuple3<>("root","before_key",false), jsonNode);
            dto.setBeforeKey(beforeKey);

            String afterKey = JsonNodeUtil.getValueByPath(new Tuple3<>("root","after_key",false), jsonNode);
            dto.setAfterKey(afterKey);

            mapper.saveI2MetaData(dto);
        }catch (Exception e){
            log.error(e.toString());
        }
    }

    /**
     * 获取查询出来的数据
     * @param sql
     * @param properties
     * @return
     */
    public static List<Map<String,Object>> selectSql(String sql, Properties properties){

        SqlSession sqlSession = null;
        List<Map<String,Object>> maps = null;
        try{
            //初始化sqlSession
            sqlSession = MybatisSessionFactory.getSqlSessionFactory(properties).openSession();
            MetaDataMapper mapper = sqlSession.getMapper(MetaDataMapper.class);
            maps = mapper.selectSql(sql);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }

        return maps;
    }

    /**
     * 获取基础信息
     * @param xid
     * @param properties
     * @return
     */
    public static List<MetaDataDTO> select(String xid, Properties properties){

        SqlSession sqlSession = null;
        List<MetaDataDTO> metaDataList = null;
        try{
            //初始化sqlSession
            sqlSession = MybatisSessionFactory.getSqlSessionFactory(properties).openSession();
            MetaDataMapper mapper = sqlSession.getMapper(MetaDataMapper.class);

            metaDataList = mapper.getMetaDataList(xid);

        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }

        return metaDataList ;
    }




}
